//
//  SNAppDelegate.m
//  DayDayHappy
//
//  Created by yutao on 14-2-19.
//  Copyright (c) 2014年 yutao. All rights reserved.
//

#import "SNAppDelegate.h"
#import "UITabBarController+Autorotate.h"
#import "UINavigationController+Autorotate.h"
#import "SNPleasureViewController.h"
#import "SNBeautyViewController.h"
#import "SNThemeViewController.h"
#import "SNVideoViewController.h"
#import "SNNavigationController.h"
#import "ShareCenter.h"
#import "BaiduMobStat.h"
#import <AdSupport/AdSupport.h>

#define kTabBarSubViewController    @"viewController"
#define kTabBarSelectImage          @"selectImage"
#define kTabBarUnSelectImage        @"unSelectImage"
#define kTabBarTopTitle             @"topTitle"
#define kTabBarBottomTitle          @"bottomTitle"


#define kSNPleasureViewController   @"SNPleasureViewController"
#define kSNBeautyViewController     @"SNBeautyViewController"
#define kSNThemeViewController      @"SNThemeViewController"
#define kSNVideoViewController      @"SNVideoViewController"
#define kSNMoreViewController       @"SNMoreViewController"


#define kSNPleasureTabBarSelectImage    @"icon_1.png"
#define kSNBeautyTabBarSelectImage      @"icon_2.png"
#define kSNThemeTabBarSelectImage       @"icon_3.png"
#define kSNVideoTabBarSelectImage       @"icon_4.png"
#define kSNMoreTabBarSelectImage        @"icon_5.png"

#define kSNPleasureTabBarUnSelectImage    @"icon1.png"
#define kSNBeautyTabBarUnSelectImage      @"icon2.png"
#define kSNThemeTabBarUnSelectImage       @"icon3.png"
#define kSNVideoTabBarUnSelectImage       @"icon4.png"
#define kSNMoreTabBarUnSelectImage        @"icon5.png"

#define kSNPleasureTabBarTopTitle    @"趣图精选"
#define kSNBeautyTabBarTopTitle      @"美图精选"
#define kSNThemeTabBarTopTitle       @"主题精选"
#define kSNVideoTabBarTopTitle       @"视频精选"
#define kSNMoreTabBarTopTitle        @"更多"


#define kSNPleasureTabBarBottomTitle    @"趣图"
#define kSNBeautyTabBarBottomTitle      @"美图"
#define kSNThemeTabBarBottomTitle       @"主题"
#define kSNVideoTabBarBottomTitle       @"视频"
#define kSNMoreTabBarBottomTitle        @"更多"

#define kTabBarCustomBackgroundImage    @"tabBarBg.png"
#define kTabBarCustomSelectImage        @"iconBack.png"

#define kUINavigationBarBackgroundImage @"navBarBg.png"

#define kAppVersion [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]
#define kBaiDuAppKey @"639cf15262"

@implementation SNAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    
    [self customUIApplicationAppearance];
    
    [self registerShareServices];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self startBaiduTracker];
//        [self config];
    });
    
//    NSLog(@"start======");
//    [self.dbHelper dropAllTable];
//    NSLog(@"end=======");
    
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = [self getTabBarController];
    [self.window makeKeyAndVisible];
    [self initBrightnessWindow];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [[ShareCenterEngine defaultEngine] handleOpenURL:url];
}

#pragma mark --------------------------Custom Method-------------------------------------

- (void)setUpNSUrlCache
{
    // Create a 4MB in-memory, 32MB disk cache
    NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:4*1024*1024
                                                      diskCapacity:32*1024*1024
                                                          diskPath:@"Happy_Cache"];
    
    // Set the shared cache to our new instance
    [NSURLCache setSharedURLCache:cache];
}

- (void)initBrightnessWindow
{
    self.brightnessWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.brightnessWindow.backgroundColor = [UIColor blackColor];
    self.brightnessWindow.windowLevel = UIWindowLevelAlert + 1;
    if ([USER_DEFAULT boolForKey:kIsHaveDayNightModle]) {
        BOOL isDayModle = [USER_DEFAULT boolForKey:kDayNightModle];
        self.brightnessWindow.alpha = isDayModle ? kDayValue : kNightValue;
    }else{
        self.brightnessWindow.alpha = 0.0;
    }
    
    self.brightnessWindow.userInteractionEnabled = NO;
    self.brightnessWindow.hidden = NO;
    
}



- (void)startBaiduTracker
{
    BaiduMobStat* statTracker = [BaiduMobStat defaultStat];
    statTracker.enableExceptionLog = YES; // 是否允许截获并发送崩溃信息，请设置YES或者NO
    statTracker.channelId = @"Cydia";//设置您的app的发布渠道
    statTracker.logStrategy = BaiduMobStatLogStrategyAppLaunch;//根据开发者设定的时间间隔接口发送 也可以使用启动时发送策略
    statTracker.enableDebugOn = YES; //打开调试模式，发布时请去除此行代码或者设置为False即可。
    //    statTracker.logSendInterval = 1; //为1时表示发送日志的时间间隔为1小时,只有 statTracker.logStrategy = BaiduMobStatLogStrategyAppLaunch这时才生效。
    statTracker.logSendWifiOnly = YES; //是否仅在WIfi情况下发送日志数据
//    statTracker.sessionResumeInterval = 1;//设置应用进入后台再回到前台为同一次session的间隔时间[0~600s],超过600s则设为600s，默认为30s
    statTracker.shortAppVersion = kAppVersion;
    NSString *adId = @"";
    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"6.0")){
        adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    }
    statTracker.adid = adId;
    
    [statTracker startWithAppId:kBaiDuAppKey];//设置您在mtj网站上添加的app的appkey
}

- (void)registerShareServices
{
    [[ShareCenterEngine defaultEngine] registerApplicationWithServicesType:3,SNShareClientTypeSinaWeibo,SNShareClientTypeQZone,SNShareClientTypeWeixinTimeline];
}

- (void)customUIApplicationAppearance
{
    [self customStatusBarStyle];
    [self customUINavigationBar];
    [self customUITabBar];
}

- (void)customStatusBarStyle
{
    UIApplication * application = [UIApplication sharedApplication];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
        [application setStatusBarStyle:UIStatusBarStyleDefault];
        self.window.frame =  CGRectMake(0,0,self.window.frame.size.width,self.window.frame.size.height);
    }
}

- (void)customUITabBar
{
    [[UITabBar appearance] setBackgroundImage:[UIImage imageNamed:kTabBarCustomBackgroundImage]];
    [[UITabBar appearance] setSelectionIndicatorImage:[UIImage imageNamed:kTabBarCustomSelectImage]];
}

- (void)customUINavigationBar
{
    [[UINavigationBar appearance] setTitleTextAttributes:
     [NSDictionary dictionaryWithObjectsAndKeys:
      [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0],
      UITextAttributeTextColor,
      [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8],
      UITextAttributeTextShadowColor,
      [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
      UITextAttributeTextShadowOffset,
      [UIFont  systemFontOfSize:22.0],
      UITextAttributeFont,
      nil]];
}

- (SNNavigationController *)getCustomNavigationControllerWithCustomDic:(NSDictionary*)dic
{
    UIViewController *viewController = (UIViewController *)[[NSClassFromString([dic objectForKey:kTabBarSubViewController]) alloc] init];
    [viewController.tabBarItem setFinishedSelectedImage:[UIImage imageNamed:[dic objectForKey:kTabBarSelectImage]] withFinishedUnselectedImage:[UIImage imageNamed:[dic objectForKey:kTabBarUnSelectImage]]];
    [viewController setTitle:[dic objectForKey:kTabBarTopTitle]];
    [viewController.tabBarItem setTitle:[dic objectForKey:kTabBarBottomTitle]];
    [viewController.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1.0],UITextAttributeTextColor, nil] forState:UIControlStateNormal];
    [viewController.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithRed:0/255.0 green:195/255.0 blue:214/255.0 alpha:1.0],UITextAttributeTextColor, nil] forState:UIControlStateSelected];
    __autoreleasing SNNavigationController * navigationController = [[SNNavigationController alloc] initWithRootViewController:viewController];
    
    //TODO   是否需要
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
        [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
    }else{
        [[navigationController navigationBar] setBackgroundImage:[UIImage imageNamed:kUINavigationBarBackgroundImage] forBarMetrics:UIBarMetricsDefault];
    }
    
    return navigationController;
}

- (NSArray *)subModleInfo
{
    __autoreleasing NSArray *modlesArray =  @[
                                              
                                              @{kTabBarSubViewController: kSNPleasureViewController,
                                                kTabBarSelectImage:kSNPleasureTabBarSelectImage,
                                                kTabBarUnSelectImage:kSNPleasureTabBarUnSelectImage,
                                                kTabBarTopTitle:kSNPleasureTabBarTopTitle,
                                                kTabBarBottomTitle:kSNPleasureTabBarBottomTitle},
                                              
                                              @{kTabBarSubViewController: kSNBeautyViewController,
                                                kTabBarSelectImage:kSNBeautyTabBarSelectImage,
                                                kTabBarUnSelectImage:kSNBeautyTabBarUnSelectImage,
                                                kTabBarTopTitle:kSNBeautyTabBarTopTitle,
                                                kTabBarBottomTitle:kSNBeautyTabBarBottomTitle},
                                              
                                              @{kTabBarSubViewController: kSNThemeViewController,
                                                kTabBarSelectImage:kSNThemeTabBarSelectImage,
                                                kTabBarUnSelectImage:kSNThemeTabBarUnSelectImage,
                                                kTabBarTopTitle:kSNThemeTabBarTopTitle,
                                                kTabBarBottomTitle:kSNThemeTabBarBottomTitle},
                                              
                                              @{kTabBarSubViewController: kSNVideoViewController,
                                                kTabBarSelectImage:kSNVideoTabBarSelectImage,
                                                kTabBarUnSelectImage:kSNVideoTabBarUnSelectImage,
                                                kTabBarTopTitle:kSNVideoTabBarTopTitle,
                                                kTabBarBottomTitle:kSNVideoTabBarBottomTitle},
                                              
                                              @{kTabBarSubViewController: kSNMoreViewController,
                                                kTabBarSelectImage:kSNMoreTabBarSelectImage,
                                                kTabBarUnSelectImage:kSNMoreTabBarUnSelectImage,
                                                kTabBarTopTitle:kSNMoreTabBarTopTitle,
                                                kTabBarBottomTitle:kSNMoreTabBarBottomTitle}
                                              
                                              ];
    return modlesArray;
}

- (UITabBarController *)getTabBarController
{
    
    NSMutableArray *navModleArray = [[NSMutableArray alloc] initWithCapacity:5];
    [[self subModleInfo] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [navModleArray addObject:[self getCustomNavigationControllerWithCustomDic:obj]];
        ;
    }];
    
    __autoreleasing UITabBarController *tabBarControl = [[UITabBarController alloc] init];
    tabBarControl.viewControllers = navModleArray;
    return tabBarControl;
}

+(SNAppDelegate *)sharedAppDelegate{
    
    return (SNAppDelegate*)[UIApplication sharedApplication].delegate;
}

- (DBHelper *)dbHelper
{
    
    return [DBHelper sharedDBHelper];
}


@end
